package com.yq.login;

import javax.security.auth.login.LoginContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/*")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String requestURI = request.getRequestURI();
        String replace = requestURI.replace(request.getContextPath() + "/user/", "");
        if ("login".equals(replace)){
            login(request,response);
        }
    }
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        session.setAttribute("username",username);
        response.getWriter().println("登录成功，即将跳转到个主页");
        response.setHeader("refresh","2;url="+request.getContextPath()+"/user/info");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        String requestURI = request.getRequestURI();
        String replace = requestURI.replace(request.getContextPath() + "/user/", "");
        if ("info".equals(replace)){
            info(request,response);
        }else if ("logout".equals(replace)){
            logout(request,response);
        }

    }

    private void info(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        response.getWriter().println(username);
        response.getWriter().println("<a href="+request.getContextPath()+"/user/logout"+">注销</a>");
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}
